// src/store/user.js

import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {}
  }),

  getters: {
    isLogin: state => !!state.token
  },

  actions: {
    loginSuccess(data) {
      this.$patch({
        token: data.token,
        userInfo: data.userInfo
      })
    },

    logout() {
      this.$reset()
      uni.removeStorageSync('user')
    },

    // 更新用户信息
    updateUserInfo(data) {
      console.log('Store: 开始更新用户信息:', data)
      console.log('Store: 更新前的用户信息:', this.userInfo)
      
      this.userInfo = {
        ...this.userInfo,
        ...data
      }
      
      console.log('Store: 更新后的用户信息:', this.userInfo)
      
      // 确保立即保存到本地存储
      try {
        const currentUser = uni.getStorageSync('user') || {}
        const updatedUser = {
          ...currentUser,
          userInfo: this.userInfo
        }
        uni.setStorageSync('user', updatedUser)
        console.log('Store: 用户信息已更新并保存到本地存储:', this.userInfo)
        
        // 验证存储是否成功
        const verifyStorage = uni.getStorageSync('user')
        console.log('Store: 验证本地存储:', verifyStorage)
        
      } catch (error) {
        console.error('Store: 保存用户信息到本地存储失败:', error)
        throw error
      }
    }
  },

  persist: {
    // 开启持久化
    enabled: true,

    storage: {
      getItem: key => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
      removeItem: key => uni.removeStorageSync(key)
    }

    // （可选）明确指定要持久化的 state，默认是全部持久化
    // paths: ['token', 'userInfo'],
  }
})
